/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useEffect } from "react";
import { useDispatch } from "dva";
import { Modal, message, Table, Alert } from "antd";
import { brandsMap_name } from "@/utils/utils";
import { useAntdTable } from "ahooks";

/**
 * 这个弹窗的列表带翻页功能
 * 产品说没那么多报价单，不需要翻页
 * 防止他反悔。
 */

const QuoteModal = props => {
  const dispatch = useDispatch();
  const { data: originList } = props;
  const [visible, setVisible] = useState(false);
  const [selectedRowsKeys, setSelectedRowsKeys] = useState([]);

  const [selectedRowsList, setSelectedRowsList] = useState([]);

  const getTableData = (res, formData, _, __) => {
    return dispatch({
      type: "order_finance/getQuoteList",
      payload: {
        ...res,
        ...formData,
        page: res.current,
      },
    }).then(res => ({
      total: res.data.total,
      list: res.data.list,
    }));
  };
  const { tableProps, loading } = useAntdTable(getTableData, {
    defaultPageSize: 5,
    form: props.form,
  });
  const columns = [
    {
      title: "报价单名称",
      dataIndex: "name",
      key: "name",
      align: "center",
    },
    {
      title: "快递品牌",
      dataIndex: "brand",
      key: "brand",
      align: "center",
      render: val => brandsMap_name(val),
    },
    {
      title: "报价单模式",
      dataIndex: "id",
      key: "id",
      align: "center",
      render: () => <div>首重 / 续重</div>,
    },
  ];
  useEffect(
    () => {
      if (originList) {
        // console.info('originList',originList)
        setSelectedRowsKeys(originList.map(item => item.id));
        setVisible(true);
      } else {
        setVisible(false);
      }
    },
    [originList]
  );

  const handleClose = () => {
    props.onClose(null);
  };
  const handleOk = () => {
    props.modalSubmit({
      id: selectedRowsKeys,
    });
  };

  const onSelectRowChange = (selectedRowKeys, selectedRows) => {
    let isCanuse, repeatBrand;
    const rowsData = selectedRowKeys
      .map(
        id =>
          selectedRows.find(item => item.id == id) || selectedRowsList.find(item => item.id == id)
      )
      .filter(item => item);
    if (rowsData.length) {
      repeatBrand = rowsData
        .map(item => item.brand)
        .reduce((pre, next) => pre + "," + next)
        .split(",")
        .filter((item, index, arr) => arr.indexOf(item) !== index)
        .toString();
    }
    isCanuse = !repeatBrand;
    if (isCanuse) {
      setSelectedRowsKeys(rowsData.map(item => item.id));
      setSelectedRowsList(rowsData);
    } else {
      message.error(`${brandsMap_name(repeatBrand)}  已经存在报价单`, 2);
    }
  };

  const rowSelectionOption = {
    selectedRowKeys: selectedRowsKeys,
    onChange: onSelectRowChange,
  };
  return (
    <Modal
      title="给驿站设置报价单"
      centered
      visible={visible}
      onCancel={handleClose}
      maskClosable
      onOk={handleOk}
      destroyOnClose
      width={700}
      okButtonProps={{ disabled: selectedRowsKeys.length == 0 }}
    >
      {selectedRowsKeys && (
        <div>
          <Alert
            message={
              <>
                已选择 <a style={{ fontWeight: 600 }}>{selectedRowsKeys.length}</a> 项&nbsp;&nbsp;
                <a style={{ marginLeft: 24 }}>清空</a>
              </>
            }
            type="info"
            showIcon
          />
        </div>
      )}

      <Table
        loading={loading}
        rowSelection={rowSelectionOption}
        columns={columns}
        rowKey="id"
        {...tableProps}
      />
      <div>注意：相同品牌的报价单，只能选择一个</div>
    </Modal>
  );
};

export default QuoteModal;
